Improved/added parameter documentation
[lhc/web/wiklou.git] / includes / filerepo / FileRepo.php
1 <?php
2 /**
3 * @defgroup FileRepo File Repository
4 *
5 * @brief This module handles how MediaWiki interacts with filesystems.
6 *
7 * @details
8 */
9
10 /**
11 * Base code for file repositories.
12 *
13 * This program is free software; you can redistribute it and/or modify
14 * it under the terms of the GNU General Public License as published by
15 * the Free Software Foundation; either version 2 of the License, or
16 * (at your option) any later version.
17 *
18 * This program is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
22 *
23 * You should have received a copy of the GNU General Public License along
24 * with this program; if not, write to the Free Software Foundation, Inc.,
25 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
26 * http://www.gnu.org/copyleft/gpl.html
27 *
28 * @file
29 * @ingroup FileRepo
30 */
31
32 /**
33 * Base class for file repositories
34 *
35 * @ingroup FileRepo
36 */
37 class FileRepo {
38 const DELETE_SOURCE = 1;
39 const OVERWRITE = 2;
40 const OVERWRITE_SAME = 4;
41 const SKIP_LOCKING = 8;
42
43 /** @var FileBackend */
44 protected $backend;
45 /** @var Array Map of zones to config */
46 protected $zones = array();
47
48 var $thumbScriptUrl, $transformVia404;
49 var $descBaseUrl, $scriptDirUrl, $scriptExtension, $articleUrl;
50 var $fetchDescription, $initialCapital;
51 var $pathDisclosureProtection = 'simple'; // 'paranoid'
52 var $descriptionCacheExpiry, $url, $thumbUrl;
53 var $hashLevels, $deletedHashLevels;
54
55 /**
56 * Factory functions for creating new files
57 * Override these in the base class
58 */
59 var $fileFactory = array( 'UnregisteredLocalFile', 'newFromTitle' );
60 var $oldFileFactory = false;
61 var $fileFactoryKey = false, $oldFileFactoryKey = false;
62
63 /**
64 * @param $info array|null
65 * @throws MWException
66 */
67 function __construct( array $info = null ) {
68 // Verify required settings presence
69 if(
70 $info === null
71 || !array_key_exists( 'name', $info )
72 || !array_key_exists( 'backend', $info )
73 ) {
74 throw new MWException( __CLASS__ . " requires an array of options having both 'name' and 'backend' keys.\n" );
75 }
76
77 // Required settings
78 $this->name = $info['name'];
79 if ( $info['backend'] instanceof FileBackend ) {
80 $this->backend = $info['backend']; // useful for testing
81 } else {
82 $this->backend = FileBackendGroup::singleton()->get( $info['backend'] );
83 }
84
85 // Optional settings that can have no value
86 $optionalSettings = array(
87 'descBaseUrl', 'scriptDirUrl', 'articleUrl', 'fetchDescription',
88 'thumbScriptUrl', 'pathDisclosureProtection', 'descriptionCacheExpiry',
89 'scriptExtension'
90 );
91 foreach ( $optionalSettings as $var ) {
92 if ( isset( $info[$var] ) ) {
93 $this->$var = $info[$var];
94 }
95 }
96
97 // Optional settings that have a default
98 $this->initialCapital = isset( $info['initialCapital'] )
99 ? $info['initialCapital']
100 : MWNamespace::isCapitalized( NS_FILE );
101 $this->url = isset( $info['url'] )
102 ? $info['url']
103 : false; // a subclass may set the URL (e.g. ForeignAPIRepo)
104 if ( isset( $info['thumbUrl'] ) ) {
105 $this->thumbUrl = $info['thumbUrl'];
106 } else {
107 $this->thumbUrl = $this->url ? "{$this->url}/thumb" : false;
108 }
109 $this->hashLevels = isset( $info['hashLevels'] )
110 ? $info['hashLevels']
111 : 2;
112 $this->deletedHashLevels = isset( $info['deletedHashLevels'] )
113 ? $info['deletedHashLevels']
114 : $this->hashLevels;
115 $this->transformVia404 = !empty( $info['transformVia404'] );
116 $this->zones = isset( $info['zones'] )
117 ? $info['zones']
118 : array();
119 // Give defaults for the basic zones...
120 foreach ( array( 'public', 'thumb', 'temp', 'deleted' ) as $zone ) {
121 if ( !isset( $this->zones[$zone] ) ) {
122 $this->zones[$zone] = array(
123 'container' => "{$this->name}-{$zone}",
124 'directory' => '' // container root
125 );
126 }
127 }
128 }
129
130 /**
131 * Get the file backend instance. Use this function wisely.
132 *
133 * @return FileBackend
134 */
135 public function getBackend() {
136 return $this->backend;
137 }
138
139 /**
140 * Get an explanatory message if this repo is read-only.
141 * This checks if an administrator disabled writes to the backend.
142 *
143 * @return string|bool Returns false if the repo is not read-only
144 */
145 public function getReadOnlyReason() {
146 return $this->backend->getReadOnlyReason();
147 }
148
149 /**
150 * Check if a single zone or list of zones is defined for usage
151 *
152 * @param $doZones Array Only do a particular zones
153 * @throws MWException
154 * @return Status
155 */
156 protected function initZones( $doZones = array() ) {
157 $status = $this->newGood();
158 foreach ( (array)$doZones as $zone ) {
159 $root = $this->getZonePath( $zone );
160 if ( $root === null ) {
161 throw new MWException( "No '$zone' zone defined in the {$this->name} repo." );
162 }
163 }
164 return $status;
165 }
166
167 /**
168 * Take all available measures to prevent web accessibility of new deleted
169 * directories, in case the user has not configured offline storage
170 *
171 * @param $dir string
172 * @return void
173 */
174 protected function initDeletedDir( $dir ) {
175 $this->backend->secure( // prevent web access & dir listings
176 array( 'dir' => $dir, 'noAccess' => true, 'noListing' => true ) );
177 }
178
179 /**
180 * Determine if a string is an mwrepo:// URL
181 *
182 * @param $url string
183 * @return bool
184 */
185 public static function isVirtualUrl( $url ) {
186 return substr( $url, 0, 9 ) == 'mwrepo://';
187 }
188
189 /**
190 * Get a URL referring to this repository, with the private mwrepo protocol.
191 * The suffix, if supplied, is considered to be unencoded, and will be
192 * URL-encoded before being returned.
193 *
194 * @param $suffix string|bool
195 * @return string
196 */
197 public function getVirtualUrl( $suffix = false ) {
198 $path = 'mwrepo://' . $this->name;
199 if ( $suffix !== false ) {
200 $path .= '/' . rawurlencode( $suffix );
201 }
202 return $path;
203 }
204
205 /**
206 * Get the URL corresponding to one of the four basic zones
207 *
208 * @param $zone String: one of: public, deleted, temp, thumb
209 * @return String or false
210 */
211 public function getZoneUrl( $zone ) {
212 switch ( $zone ) {
213 case 'public':
214 return $this->url;
215 case 'temp':
216 return "{$this->url}/temp";
217 case 'deleted':
218 return false; // no public URL
219 case 'thumb':
220 return $this->thumbUrl;
221 default:
222 return false;
223 }
224 }
225
226 /**
227 * Get the backend storage path corresponding to a virtual URL.
228 * Use this function wisely.
229 *
230 * @param $url string
231 * @throws MWException
232 * @return string
233 */
234 public function resolveVirtualUrl( $url ) {
235 if ( substr( $url, 0, 9 ) != 'mwrepo://' ) {
236 throw new MWException( __METHOD__.': unknown protocol' );
237 }
238 $bits = explode( '/', substr( $url, 9 ), 3 );
239 if ( count( $bits ) != 3 ) {
240 throw new MWException( __METHOD__.": invalid mwrepo URL: $url" );
241 }
242 list( $repo, $zone, $rel ) = $bits;
243 if ( $repo !== $this->name ) {
244 throw new MWException( __METHOD__.": fetching from a foreign repo is not supported" );
245 }
246 $base = $this->getZonePath( $zone );
247 if ( !$base ) {
248 throw new MWException( __METHOD__.": invalid zone: $zone" );
249 }
250 return $base . '/' . rawurldecode( $rel );
251 }
252
253 /**
254 * The the storage container and base path of a zone
255 *
256 * @param $zone string
257 * @return Array (container, base path) or (null, null)
258 */
259 protected function getZoneLocation( $zone ) {
260 if ( !isset( $this->zones[$zone] ) ) {
261 return array( null, null ); // bogus
262 }
263 return array( $this->zones[$zone]['container'], $this->zones[$zone]['directory'] );
264 }
265
266 /**
267 * Get the storage path corresponding to one of the zones
268 *
269 * @param $zone string
270 * @return string|null Returns null if the zone is not defined
271 */
272 public function getZonePath( $zone ) {
273 list( $container, $base ) = $this->getZoneLocation( $zone );
274 if ( $container === null || $base === null ) {
275 return null;
276 }
277 $backendName = $this->backend->getName();
278 if ( $base != '' ) { // may not be set
279 $base = "/{$base}";
280 }
281 return "mwstore://$backendName/{$container}{$base}";
282 }
283
284 /**
285 * Create a new File object from the local repository
286 *
287 * @param $title Mixed: Title object or string
288 * @param $time Mixed: Time at which the image was uploaded.
289 * If this is specified, the returned object will be an
290 * instance of the repository's old file class instead of a
291 * current file. Repositories not supporting version control
292 * should return false if this parameter is set.
293 * @return File|null A File, or null if passed an invalid Title
294 */
295 public function newFile( $title, $time = false ) {
296 $title = File::normalizeTitle( $title );
297 if ( !$title ) {
298 return null;
299 }
300 if ( $time ) {
301 if ( $this->oldFileFactory ) {
302 return call_user_func( $this->oldFileFactory, $title, $this, $time );
303 } else {
304 return false;
305 }
306 } else {
307 return call_user_func( $this->fileFactory, $title, $this );
308 }
309 }
310
311 /**
312 * Find an instance of the named file created at the specified time
313 * Returns false if the file does not exist. Repositories not supporting
314 * version control should return false if the time is specified.
315 *
316 * @param $title Mixed: Title object or string
317 * @param $options array Associative array of options:
318 * time: requested time for a specific file version, or false for the
319 * current version. An image object will be returned which was
320 * created at the specified time (which may be archived or current).
321 *
322 * ignoreRedirect: If true, do not follow file redirects
323 *
324 * private: If true, return restricted (deleted) files if the current
325 * user is allowed to view them. Otherwise, such files will not
326 * be found.
327 * @return File|bool False on failure
328 */
329 public function findFile( $title, $options = array() ) {
330 $title = File::normalizeTitle( $title );
331 if ( !$title ) {
332 return false;
333 }
334 $time = isset( $options['time'] ) ? $options['time'] : false;
335 # First try the current version of the file to see if it precedes the timestamp
336 $img = $this->newFile( $title );
337 if ( !$img ) {
338 return false;
339 }
340 if ( $img->exists() && ( !$time || $img->getTimestamp() == $time ) ) {
341 return $img;
342 }
343 # Now try an old version of the file
344 if ( $time !== false ) {
345 $img = $this->newFile( $title, $time );
346 if ( $img && $img->exists() ) {
347 if ( !$img->isDeleted( File::DELETED_FILE ) ) {
348 return $img; // always OK
349 } elseif ( !empty( $options['private'] ) && $img->userCan( File::DELETED_FILE ) ) {
350 return $img;
351 }
352 }
353 }
354
355 # Now try redirects
356 if ( !empty( $options['ignoreRedirect'] ) ) {
357 return false;
358 }
359 $redir = $this->checkRedirect( $title );
360 if ( $redir && $title->getNamespace() == NS_FILE) {
361 $img = $this->newFile( $redir );
362 if ( !$img ) {
363 return false;
364 }
365 if ( $img->exists() ) {
366 $img->redirectedFrom( $title->getDBkey() );
367 return $img;
368 }
369 }
370 return false;
371 }
372
373 /**
374 * Find many files at once.
375 *
376 * @param $items array An array of titles, or an array of findFile() options with
377 * the "title" option giving the title. Example:
378 *
379 * $findItem = array( 'title' => $title, 'private' => true );
380 * $findBatch = array( $findItem );
381 * $repo->findFiles( $findBatch );
382 * @return array
383 */
384 public function findFiles( array $items ) {
385 $result = array();
386 foreach ( $items as $item ) {
387 if ( is_array( $item ) ) {
388 $title = $item['title'];
389 $options = $item;
390 unset( $options['title'] );
391 } else {
392 $title = $item;
393 $options = array();
394 }
395 $file = $this->findFile( $title, $options );
396 if ( $file ) {
397 $result[$file->getTitle()->getDBkey()] = $file;
398 }
399 }
400 return $result;
401 }
402
403 /**
404 * Find an instance of the file with this key, created at the specified time
405 * Returns false if the file does not exist. Repositories not supporting
406 * version control should return false if the time is specified.
407 *
408 * @param $sha1 String base 36 SHA-1 hash
409 * @param $options array Option array, same as findFile().
410 * @return File|bool False on failure
411 */
412 public function findFileFromKey( $sha1, $options = array() ) {
413 $time = isset( $options['time'] ) ? $options['time'] : false;
414 # First try to find a matching current version of a file...
415 if ( $this->fileFactoryKey ) {
416 $img = call_user_func( $this->fileFactoryKey, $sha1, $this, $time );
417 } else {
418 return false; // find-by-sha1 not supported
419 }
420 if ( $img && $img->exists() ) {
421 return $img;
422 }
423 # Now try to find a matching old version of a file...
424 if ( $time !== false && $this->oldFileFactoryKey ) { // find-by-sha1 supported?
425 $img = call_user_func( $this->oldFileFactoryKey, $sha1, $this, $time );
426 if ( $img && $img->exists() ) {
427 if ( !$img->isDeleted( File::DELETED_FILE ) ) {
428 return $img; // always OK
429 } elseif ( !empty( $options['private'] ) && $img->userCan( File::DELETED_FILE ) ) {
430 return $img;
431 }
432 }
433 }
434 return false;
435 }
436
437 /**
438 * Get an array or iterator of file objects for files that have a given
439 * SHA-1 content hash.
440 *
441 * STUB
442 * @param $hash
443 * @return array
444 */
445 public function findBySha1( $hash ) {
446 return array();
447 }
448
449 /**
450 * Get the public root URL of the repository
451 *
452 * @return string
453 */
454 public function getRootUrl() {
455 return $this->url;
456 }
457
458 /**
459 * Get the URL of thumb.php
460 *
461 * @return string
462 */
463 public function getThumbScriptUrl() {
464 return $this->thumbScriptUrl;
465 }
466
467 /**
468 * Returns true if the repository can transform files via a 404 handler
469 *
470 * @return bool
471 */
472 public function canTransformVia404() {
473 return $this->transformVia404;
474 }
475
476 /**
477 * Get the name of an image from its title object
478 *
479 * @param $title Title
480 * @return String
481 */
482 public function getNameFromTitle( Title $title ) {
483 global $wgContLang;
484 if ( $this->initialCapital != MWNamespace::isCapitalized( NS_FILE ) ) {
485 $name = $title->getUserCaseDBKey();
486 if ( $this->initialCapital ) {
487 $name = $wgContLang->ucfirst( $name );
488 }
489 } else {
490 $name = $title->getDBkey();
491 }
492 return $name;
493 }
494
495 /**
496 * Get the public zone root storage directory of the repository
497 *
498 * @return string
499 */
500 public function getRootDirectory() {
501 return $this->getZonePath( 'public' );
502 }
503
504 /**
505 * Get a relative path including trailing slash, e.g. f/fa/
506 * If the repo is not hashed, returns an empty string
507 *
508 * @param $name string Name of file
509 * @return string
510 */
511 public function getHashPath( $name ) {
512 return self::getHashPathForLevel( $name, $this->hashLevels );
513 }
514
515 /**
516 * Get a relative path including trailing slash, e.g. f/fa/
517 * If the repo is not hashed, returns an empty string
518 *
519 * @param $suffix string Basename of file from FileRepo::storeTemp()
520 * @return string
521 */
522 public function getTempHashPath( $suffix ) {
523 $parts = explode( '!', $suffix, 2 ); // format is <timestamp>!<name> or just <name>
524 $name = isset( $parts[1] ) ? $parts[1] : $suffix; // hash path is not based on timestamp
525 return self::getHashPathForLevel( $name, $this->hashLevels );
526 }
527
528 /**
529 * @param $name
530 * @param $levels
531 * @return string
532 */
533 protected static function getHashPathForLevel( $name, $levels ) {
534 if ( $levels == 0 ) {
535 return '';
536 } else {
537 $hash = md5( $name );
538 $path = '';
539 for ( $i = 1; $i <= $levels; $i++ ) {
540 $path .= substr( $hash, 0, $i ) . '/';
541 }
542 return $path;
543 }
544 }
545
546 /**
547 * Get the number of hash directory levels
548 *
549 * @return integer
550 */
551 public function getHashLevels() {
552 return $this->hashLevels;
553 }
554
555 /**
556 * Get the name of this repository, as specified by $info['name]' to the constructor
557 *
558 * @return string
559 */
560 public function getName() {
561 return $this->name;
562 }
563
564 /**
565 * Make an url to this repo
566 *
567 * @param $query mixed Query string to append
568 * @param $entry string Entry point; defaults to index
569 * @return string|bool False on failure
570 */
571 public function makeUrl( $query = '', $entry = 'index' ) {
572 if ( isset( $this->scriptDirUrl ) ) {
573 $ext = isset( $this->scriptExtension ) ? $this->scriptExtension : '.php';
574 return wfAppendQuery( "{$this->scriptDirUrl}/{$entry}{$ext}", $query );
575 }
576 return false;
577 }
578
579 /**
580 * Get the URL of an image description page. May return false if it is
581 * unknown or not applicable. In general this should only be called by the
582 * File class, since it may return invalid results for certain kinds of
583 * repositories. Use File::getDescriptionUrl() in user code.
584 *
585 * In particular, it uses the article paths as specified to the repository
586 * constructor, whereas local repositories use the local Title functions.
587 *
588 * @param $name string
589 * @return string
590 */
591 public function getDescriptionUrl( $name ) {
592 $encName = wfUrlencode( $name );
593 if ( !is_null( $this->descBaseUrl ) ) {
594 # "http://example.com/wiki/Image:"
595 return $this->descBaseUrl . $encName;
596 }
597 if ( !is_null( $this->articleUrl ) ) {
598 # "http://example.com/wiki/$1"
599 #
600 # We use "Image:" as the canonical namespace for
601 # compatibility across all MediaWiki versions.
602 return str_replace( '$1',
603 "Image:$encName", $this->articleUrl );
604 }
605 if ( !is_null( $this->scriptDirUrl ) ) {
606 # "http://example.com/w"
607 #
608 # We use "Image:" as the canonical namespace for
609 # compatibility across all MediaWiki versions,
610 # and just sort of hope index.php is right. ;)
611 return $this->makeUrl( "title=Image:$encName" );
612 }
613 return false;
614 }
615
616 /**
617 * Get the URL of the content-only fragment of the description page. For
618 * MediaWiki this means action=render. This should only be called by the
619 * repository's file class, since it may return invalid results. User code
620 * should use File::getDescriptionText().
621 *
622 * @param $name String: name of image to fetch
623 * @param $lang String: language to fetch it in, if any.
624 * @return string
625 */
626 public function getDescriptionRenderUrl( $name, $lang = null ) {
627 $query = 'action=render';
628 if ( !is_null( $lang ) ) {
629 $query .= '&uselang=' . $lang;
630 }
631 if ( isset( $this->scriptDirUrl ) ) {
632 return $this->makeUrl(
633 'title=' .
634 wfUrlencode( 'Image:' . $name ) .
635 "&$query" );
636 } else {
637 $descUrl = $this->getDescriptionUrl( $name );
638 if ( $descUrl ) {
639 return wfAppendQuery( $descUrl, $query );
640 } else {
641 return false;
642 }
643 }
644 }
645
646 /**
647 * Get the URL of the stylesheet to apply to description pages
648 *
649 * @return string|bool False on failure
650 */
651 public function getDescriptionStylesheetUrl() {
652 if ( isset( $this->scriptDirUrl ) ) {
653 return $this->makeUrl( 'title=MediaWiki:Filepage.css&' .
654 wfArrayToCGI( Skin::getDynamicStylesheetQuery() ) );
655 }
656 return false;
657 }
658
659 /**
660 * Store a file to a given destination.
661 *
662 * @param $srcPath String: source FS path, storage path, or virtual URL
663 * @param $dstZone String: destination zone
664 * @param $dstRel String: destination relative path
665 * @param $flags Integer: bitwise combination of the following flags:
666 * self::DELETE_SOURCE Delete the source file after upload
667 * self::OVERWRITE Overwrite an existing destination file instead of failing
668 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
669 * same contents as the source
670 * self::SKIP_LOCKING Skip any file locking when doing the store
671 * @return FileRepoStatus
672 */
673 public function store( $srcPath, $dstZone, $dstRel, $flags = 0 ) {
674 $this->assertWritableRepo(); // fail out if read-only
675
676 $status = $this->storeBatch( array( array( $srcPath, $dstZone, $dstRel ) ), $flags );
677 if ( $status->successCount == 0 ) {
678 $status->ok = false;
679 }
680
681 return $status;
682 }
683
684 /**
685 * Store a batch of files
686 *
687 * @param $triplets Array: (src, dest zone, dest rel) triplets as per store()
688 * @param $flags Integer: bitwise combination of the following flags:
689 * self::DELETE_SOURCE Delete the source file after upload
690 * self::OVERWRITE Overwrite an existing destination file instead of failing
691 * self::OVERWRITE_SAME Overwrite the file if the destination exists and has the
692 * same contents as the source
693 * self::SKIP_LOCKING Skip any file locking when doing the store
694 * @throws MWException
695 * @return FileRepoStatus
696 */
697 public function storeBatch( array $triplets, $flags = 0 ) {
698 $this->assertWritableRepo(); // fail out if read-only
699
700 $status = $this->newGood();
701 $backend = $this->backend; // convenience
702
703 $operations = array();
704 $sourceFSFilesToDelete = array(); // cleanup for disk source files
705 // Validate each triplet and get the store operation...
706 foreach ( $triplets as $triplet ) {
707 list( $srcPath, $dstZone, $dstRel ) = $triplet;
708 wfDebug( __METHOD__
709 . "( \$src='$srcPath', \$dstZone='$dstZone', \$dstRel='$dstRel' )\n"
710 );
711
712 // Resolve destination path
713 $root = $this->getZonePath( $dstZone );
714 if ( !$root ) {
715 throw new MWException( "Invalid zone: $dstZone" );
716 }
717 if ( !$this->validateFilename( $dstRel ) ) {
718 throw new MWException( 'Validation error in $dstRel' );
719 }
720 $dstPath = "$root/$dstRel";
721 $dstDir = dirname( $dstPath );
722 // Create destination directories for this triplet
723 if ( !$backend->prepare( array( 'dir' => $dstDir ) )->isOK() ) {
724 return $this->newFatal( 'directorycreateerror', $dstDir );
725 }
726
727 if ( $dstZone == 'deleted' ) {
728 $this->initDeletedDir( $dstDir );
729 }
730
731 // Resolve source to a storage path if virtual
732 $srcPath = $this->resolveToStoragePath( $srcPath );
733
734 // Get the appropriate file operation
735 if ( FileBackend::isStoragePath( $srcPath ) ) {
736 $opName = ( $flags & self::DELETE_SOURCE ) ? 'move' : 'copy';
737 } else {
738 $opName = 'store';
739 if ( $flags & self::DELETE_SOURCE ) {
740 $sourceFSFilesToDelete[] = $srcPath;
741 }
742 }
743 $operations[] = array(
744 'op' => $opName,
745 'src' => $srcPath,
746 'dst' => $dstPath,
747 'overwrite' => $flags & self::OVERWRITE,
748 'overwriteSame' => $flags & self::OVERWRITE_SAME,
749 );
750 }
751
752 // Execute the store operation for each triplet
753 $opts = array( 'force' => true );
754 if ( $flags & self::SKIP_LOCKING ) {
755 $opts['nonLocking'] = true;
756 }
757 $status->merge( $backend->doOperations( $operations, $opts ) );
758 // Cleanup for disk source files...
759 foreach ( $sourceFSFilesToDelete as $file ) {
760 wfSuppressWarnings();
761 unlink( $file ); // FS cleanup
762 wfRestoreWarnings();
763 }
764
765 return $status;
766 }
767
768 /**
769 * Deletes a batch of files.
770 * Each file can be a (zone, rel) pair, virtual url, storage path.
771 * It will try to delete each file, but ignores any errors that may occur.
772 *
773 * @param $files array List of files to delete
774 * @param $flags Integer: bitwise combination of the following flags:
775 * self::SKIP_LOCKING Skip any file locking when doing the deletions
776 * @return FileRepoStatus
777 */
778 public function cleanupBatch( array $files, $flags = 0 ) {
779 $this->assertWritableRepo(); // fail out if read-only
780
781 $status = $this->newGood();
782
783 $operations = array();
784 foreach ( $files as $path ) {
785 if ( is_array( $path ) ) {
786 // This is a pair, extract it
787 list( $zone, $rel ) = $path;
788 $path = $this->getZonePath( $zone ) . "/$rel";
789 } else {
790 // Resolve source to a storage path if virtual
791 $path = $this->resolveToStoragePath( $path );
792 }
793 $operations[] = array( 'op' => 'delete', 'src' => $path );
794 }
795 // Actually delete files from storage...
796 $opts = array( 'force' => true );
797 if ( $flags & self::SKIP_LOCKING ) {
798 $opts['nonLocking'] = true;
799 }
800 $status->merge( $this->backend->doOperations( $operations, $opts ) );
801
802 return $status;
803 }
804
805 /**
806 * Import a file from the local file system into the repo.
807 * This does no locking nor journaling and overrides existing files.
808 * This function can be used to write to otherwise read-only foreign repos.
809 * This is intended for copying generated thumbnails into the repo.
810 *
811 * @param $src string File system path
812 * @param $dst string Virtual URL or storage path
813 * @return FileRepoStatus
814 */
815 final public function quickImport( $src, $dst ) {
816 return $this->quickImportBatch( array( array( $src, $dst ) ) );
817 }
818
819 /**
820 * Purge a file from the repo. This does no locking nor journaling.
821 * This function can be used to write to otherwise read-only foreign repos.
822 * This is intended for purging thumbnails.
823 *
824 * @param $path string Virtual URL or storage path
825 * @return FileRepoStatus
826 */
827 final public function quickPurge( $path ) {
828 return $this->quickPurgeBatch( array( $path ) );
829 }
830
831 /**
832 * Deletes a directory if empty.
833 * This function can be used to write to otherwise read-only foreign repos.
834 *
835 * @param $dir string Virtual URL (or storage path) of directory to clean
836 * @return Status
837 */
838 public function quickCleanDir( $dir ) {
839 $status = $this->newGood();
840 $status->merge( $this->backend->clean(
841 array( 'dir' => $this->resolveToStoragePath( $dir ) ) ) );
842
843 return $status;
844 }
845
846 /**
847 * Import a batch of files from the local file system into the repo.
848 * This does no locking nor journaling and overrides existing files.
849 * This function can be used to write to otherwise read-only foreign repos.
850 * This is intended for copying generated thumbnails into the repo.
851 *
852 * @param $pairs Array List of tuples (file system path, virtual URL or storage path)
853 * @return FileRepoStatus
854 */
855 public function quickImportBatch( array $pairs ) {
856 $status = $this->newGood();
857 $operations = array();
858 foreach ( $pairs as $pair ) {
859 list ( $src, $dst ) = $pair;
860 $operations[] = array(
861 'op' => 'store',
862 'src' => $src,
863 'dst' => $this->resolveToStoragePath( $dst ),
864 'overwrite' => true
865 );
866 $this->backend->prepare( array( 'dir' => dirname( $dst ) ) );
867 }
868 $status->merge( $this->backend->doOperations( $operations,
869 array( 'force' => 1, 'nonLocking' => 1, 'allowStale' => 1, 'nonJournaled' => 1 )
870 ) );
871
872 return $status;
873 }
874
875 /**
876 * Purge a batch of files from the repo.
877 * This function can be used to write to otherwise read-only foreign repos.
878 * This does no locking nor journaling and is intended for purging thumbnails.
879 *
880 * @param $paths Array List of virtual URLs or storage paths
881 * @return FileRepoStatus
882 */
883 public function quickPurgeBatch( array $paths ) {
884 $status = $this->newGood();
885 $operations = array();
886 foreach ( $paths as $path ) {
887 $operations[] = array(
888 'op' => 'delete',
889 'src' => $this->resolveToStoragePath( $path ),
890 'ignoreMissingSource' => true
891 );
892 }
893 $status->merge( $this->backend->doOperations( $operations,
894 array( 'force' => 1, 'nonLocking' => 1, 'allowStale' => 1, 'nonJournaled' => 1 )
895 ) );
896
897 return $status;
898 }
899
900 /**
901 * Pick a random name in the temp zone and store a file to it.
902 * Returns a FileRepoStatus object with the file Virtual URL in the value,
903 * file can later be disposed using FileRepo::freeTemp().
904 *
905 * @param $originalName String: the base name of the file as specified
906 * by the user. The file extension will be maintained.
907 * @param $srcPath String: the current location of the file.
908 * @return FileRepoStatus object with the URL in the value.
909 */
910 public function storeTemp( $originalName, $srcPath ) {
911 $this->assertWritableRepo(); // fail out if read-only
912
913 $date = gmdate( "YmdHis" );
914 $hashPath = $this->getHashPath( $originalName );
915 $dstRel = "{$hashPath}{$date}!{$originalName}";
916 $dstUrlRel = $hashPath . $date . '!' . rawurlencode( $originalName );
917
918 $result = $this->store( $srcPath, 'temp', $dstRel, self::SKIP_LOCKING );
919 $result->value = $this->getVirtualUrl( 'temp' ) . '/' . $dstUrlRel;
920
921 return $result;
922 }
923
924 /**
925 * Concatenate a list of files into a target file location.
926 *
927 * @param $srcPaths Array Ordered list of source virtual URLs/storage paths
928 * @param $dstPath String Target file system path
929 * @param $flags Integer: bitwise combination of the following flags:
930 * self::DELETE_SOURCE Delete the source files
931 * @return FileRepoStatus
932 */
933 public function concatenate( array $srcPaths, $dstPath, $flags = 0 ) {
934 $this->assertWritableRepo(); // fail out if read-only
935
936 $status = $this->newGood();
937
938 $sources = array();
939 $deleteOperations = array(); // post-concatenate ops
940 foreach ( $srcPaths as $srcPath ) {
941 // Resolve source to a storage path if virtual
942 $source = $this->resolveToStoragePath( $srcPath );
943 $sources[] = $source; // chunk to merge
944 if ( $flags & self::DELETE_SOURCE ) {
945 $deleteOperations[] = array( 'op' => 'delete', 'src' => $source );
946 }
947 }
948
949 // Concatenate the chunks into one FS file
950 $params = array( 'srcs' => $sources, 'dst' => $dstPath );
951 $status->merge( $this->backend->concatenate( $params ) );
952 if ( !$status->isOK() ) {
953 return $status;
954 }
955
956 // Delete the sources if required
957 if ( $deleteOperations ) {
958 $opts = array( 'force' => true );
959 $status->merge( $this->backend->doOperations( $deleteOperations, $opts ) );
960 }
961
962 // Make sure status is OK, despite any $deleteOperations fatals
963 $status->setResult( true );
964
965 return $status;
966 }
967
968 /**
969 * Remove a temporary file or mark it for garbage collection
970 *
971 * @param $virtualUrl String: the virtual URL returned by FileRepo::storeTemp()
972 * @return Boolean: true on success, false on failure
973 */
974 public function freeTemp( $virtualUrl ) {
975 $this->assertWritableRepo(); // fail out if read-only
976
977 $temp = "mwrepo://{$this->name}/temp";
978 if ( substr( $virtualUrl, 0, strlen( $temp ) ) != $temp ) {
979 wfDebug( __METHOD__.": Invalid temp virtual URL\n" );
980 return false;
981 }
982 $path = $this->resolveVirtualUrl( $virtualUrl );
983
984 return $this->cleanupBatch( array( $path ), self::SKIP_LOCKING )->isOK();
985 }
986
987 /**
988 * Copy or move a file either from a storage path, virtual URL,
989 * or FS path, into this repository at the specified destination location.
990 *
991 * Returns a FileRepoStatus object. On success, the value contains "new" or
992 * "archived", to indicate whether the file was new with that name.
993 *
994 * @param $srcPath String: the source FS path, storage path, or URL
995 * @param $dstRel String: the destination relative path
996 * @param $archiveRel String: the relative path where the existing file is to
997 * be archived, if there is one. Relative to the public zone root.
998 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
999 * that the source file should be deleted if possible
1000 * @return FileRepoStatus
1001 */
1002 public function publish( $srcPath, $dstRel, $archiveRel, $flags = 0 ) {
1003 $this->assertWritableRepo(); // fail out if read-only
1004
1005 $status = $this->publishBatch( array( array( $srcPath, $dstRel, $archiveRel ) ), $flags );
1006 if ( $status->successCount == 0 ) {
1007 $status->ok = false;
1008 }
1009 if ( isset( $status->value[0] ) ) {
1010 $status->value = $status->value[0];
1011 } else {
1012 $status->value = false;
1013 }
1014
1015 return $status;
1016 }
1017
1018 /**
1019 * Publish a batch of files
1020 *
1021 * @param $triplets Array: (source, dest, archive) triplets as per publish()
1022 * @param $flags Integer: bitfield, may be FileRepo::DELETE_SOURCE to indicate
1023 * that the source files should be deleted if possible
1024 * @throws MWException
1025 * @return FileRepoStatus
1026 */
1027 public function publishBatch( array $triplets, $flags = 0 ) {
1028 $this->assertWritableRepo(); // fail out if read-only
1029
1030 $backend = $this->backend; // convenience
1031 // Try creating directories
1032 $status = $this->initZones( 'public' );
1033 if ( !$status->isOK() ) {
1034 return $status;
1035 }
1036
1037 $status = $this->newGood( array() );
1038
1039 $operations = array();
1040 $sourceFSFilesToDelete = array(); // cleanup for disk source files
1041 // Validate each triplet and get the store operation...
1042 foreach ( $triplets as $i => $triplet ) {
1043 list( $srcPath, $dstRel, $archiveRel ) = $triplet;
1044 // Resolve source to a storage path if virtual
1045 $srcPath = $this->resolveToStoragePath( $srcPath );
1046 if ( !$this->validateFilename( $dstRel ) ) {
1047 throw new MWException( 'Validation error in $dstRel' );
1048 }
1049 if ( !$this->validateFilename( $archiveRel ) ) {
1050 throw new MWException( 'Validation error in $archiveRel' );
1051 }
1052
1053 $publicRoot = $this->getZonePath( 'public' );
1054 $dstPath = "$publicRoot/$dstRel";
1055 $archivePath = "$publicRoot/$archiveRel";
1056
1057 $dstDir = dirname( $dstPath );
1058 $archiveDir = dirname( $archivePath );
1059 // Abort immediately on directory creation errors since they're likely to be repetitive
1060 if ( !$backend->prepare( array( 'dir' => $dstDir ) )->isOK() ) {
1061 return $this->newFatal( 'directorycreateerror', $dstDir );
1062 }
1063 if ( !$backend->prepare( array( 'dir' => $archiveDir ) )->isOK() ) {
1064 return $this->newFatal( 'directorycreateerror', $archiveDir );
1065 }
1066
1067 // Archive destination file if it exists
1068 if ( $backend->fileExists( array( 'src' => $dstPath ) ) ) {
1069 // Check if the archive file exists
1070 // This is a sanity check to avoid data loss. In UNIX, the rename primitive
1071 // unlinks the destination file if it exists. DB-based synchronisation in
1072 // publishBatch's caller should prevent races. In Windows there's no
1073 // problem because the rename primitive fails if the destination exists.
1074 if ( $backend->fileExists( array( 'src' => $archivePath ) ) ) {
1075 $operations[] = array( 'op' => 'null' );
1076 continue;
1077 } else {
1078 $operations[] = array(
1079 'op' => 'move',
1080 'src' => $dstPath,
1081 'dst' => $archivePath
1082 );
1083 }
1084 $status->value[$i] = 'archived';
1085 } else {
1086 $status->value[$i] = 'new';
1087 }
1088 // Copy (or move) the source file to the destination
1089 if ( FileBackend::isStoragePath( $srcPath ) ) {
1090 if ( $flags & self::DELETE_SOURCE ) {
1091 $operations[] = array(
1092 'op' => 'move',
1093 'src' => $srcPath,
1094 'dst' => $dstPath
1095 );
1096 } else {
1097 $operations[] = array(
1098 'op' => 'copy',
1099 'src' => $srcPath,
1100 'dst' => $dstPath
1101 );
1102 }
1103 } else { // FS source path
1104 $operations[] = array(
1105 'op' => 'store',
1106 'src' => $srcPath,
1107 'dst' => $dstPath
1108 );
1109 if ( $flags & self::DELETE_SOURCE ) {
1110 $sourceFSFilesToDelete[] = $srcPath;
1111 }
1112 }
1113 }
1114
1115 // Execute the operations for each triplet
1116 $opts = array( 'force' => true );
1117 $status->merge( $backend->doOperations( $operations, $opts ) );
1118 // Cleanup for disk source files...
1119 foreach ( $sourceFSFilesToDelete as $file ) {
1120 wfSuppressWarnings();
1121 unlink( $file ); // FS cleanup
1122 wfRestoreWarnings();
1123 }
1124
1125 return $status;
1126 }
1127
1128 /**
1129 * Deletes a directory if empty.
1130 *
1131 * @param $dir string Virtual URL (or storage path) of directory to clean
1132 * @return Status
1133 */
1134 public function cleanDir( $dir ) {
1135 $this->assertWritableRepo(); // fail out if read-only
1136
1137 $status = $this->newGood();
1138 $status->merge( $this->backend->clean(
1139 array( 'dir' => $this->resolveToStoragePath( $dir ) ) ) );
1140
1141 return $status;
1142 }
1143
1144 /**
1145 * Checks existence of a a file
1146 *
1147 * @param $file string Virtual URL (or storage path) of file to check
1148 * @return bool
1149 */
1150 public function fileExists( $file ) {
1151 $result = $this->fileExistsBatch( array( $file ) );
1152 return $result[0];
1153 }
1154
1155 /**
1156 * Checks existence of an array of files.
1157 *
1158 * @param $files Array: Virtual URLs (or storage paths) of files to check
1159 * @return array|bool Either array of files and existence flags, or false
1160 */
1161 public function fileExistsBatch( array $files ) {
1162 $result = array();
1163 foreach ( $files as $key => $file ) {
1164 $file = $this->resolveToStoragePath( $file );
1165 $result[$key] = $this->backend->fileExists( array( 'src' => $file ) );
1166 }
1167 return $result;
1168 }
1169
1170 /**
1171 * Move a file to the deletion archive.
1172 * If no valid deletion archive exists, this may either delete the file
1173 * or throw an exception, depending on the preference of the repository
1174 *
1175 * @param $srcRel Mixed: relative path for the file to be deleted
1176 * @param $archiveRel Mixed: relative path for the archive location.
1177 * Relative to a private archive directory.
1178 * @return FileRepoStatus object
1179 */
1180 public function delete( $srcRel, $archiveRel ) {
1181 $this->assertWritableRepo(); // fail out if read-only
1182
1183 return $this->deleteBatch( array( array( $srcRel, $archiveRel ) ) );
1184 }
1185
1186 /**
1187 * Move a group of files to the deletion archive.
1188 *
1189 * If no valid deletion archive is configured, this may either delete the
1190 * file or throw an exception, depending on the preference of the repository.
1191 *
1192 * The overwrite policy is determined by the repository -- currently LocalRepo
1193 * assumes a naming scheme in the deleted zone based on content hash, as
1194 * opposed to the public zone which is assumed to be unique.
1195 *
1196 * @param $sourceDestPairs Array of source/destination pairs. Each element
1197 * is a two-element array containing the source file path relative to the
1198 * public root in the first element, and the archive file path relative
1199 * to the deleted zone root in the second element.
1200 * @throws MWException
1201 * @return FileRepoStatus
1202 */
1203 public function deleteBatch( array $sourceDestPairs ) {
1204 $this->assertWritableRepo(); // fail out if read-only
1205
1206 // Try creating directories
1207 $status = $this->initZones( array( 'public', 'deleted' ) );
1208 if ( !$status->isOK() ) {
1209 return $status;
1210 }
1211
1212 $status = $this->newGood();
1213
1214 $backend = $this->backend; // convenience
1215 $operations = array();
1216 // Validate filenames and create archive directories
1217 foreach ( $sourceDestPairs as $pair ) {
1218 list( $srcRel, $archiveRel ) = $pair;
1219 if ( !$this->validateFilename( $srcRel ) ) {
1220 throw new MWException( __METHOD__.':Validation error in $srcRel' );
1221 } elseif ( !$this->validateFilename( $archiveRel ) ) {
1222 throw new MWException( __METHOD__.':Validation error in $archiveRel' );
1223 }
1224
1225 $publicRoot = $this->getZonePath( 'public' );
1226 $srcPath = "{$publicRoot}/$srcRel";
1227
1228 $deletedRoot = $this->getZonePath( 'deleted' );
1229 $archivePath = "{$deletedRoot}/{$archiveRel}";
1230 $archiveDir = dirname( $archivePath ); // does not touch FS
1231
1232 // Create destination directories
1233 if ( !$backend->prepare( array( 'dir' => $archiveDir ) )->isOK() ) {
1234 return $this->newFatal( 'directorycreateerror', $archiveDir );
1235 }
1236 $this->initDeletedDir( $archiveDir );
1237
1238 $operations[] = array(
1239 'op' => 'move',
1240 'src' => $srcPath,
1241 'dst' => $archivePath,
1242 // We may have 2+ identical files being deleted,
1243 // all of which will map to the same destination file
1244 'overwriteSame' => true // also see bug 31792
1245 );
1246 }
1247
1248 // Move the files by execute the operations for each pair.
1249 // We're now committed to returning an OK result, which will
1250 // lead to the files being moved in the DB also.
1251 $opts = array( 'force' => true );
1252 $status->merge( $backend->doOperations( $operations, $opts ) );
1253
1254 return $status;
1255 }
1256
1257 /**
1258 * Delete files in the deleted directory if they are not referenced in the filearchive table
1259 *
1260 * STUB
1261 */
1262 public function cleanupDeletedBatch( array $storageKeys ) {
1263 $this->assertWritableRepo();
1264 }
1265
1266 /**
1267 * Get a relative path for a deletion archive key,
1268 * e.g. s/z/a/ for sza251lrxrc1jad41h5mgilp8nysje52.jpg
1269 *
1270 * @param $key string
1271 * @return string
1272 */
1273 public function getDeletedHashPath( $key ) {
1274 $path = '';
1275 for ( $i = 0; $i < $this->deletedHashLevels; $i++ ) {
1276 $path .= $key[$i] . '/';
1277 }
1278 return $path;
1279 }
1280
1281 /**
1282 * If a path is a virtual URL, resolve it to a storage path.
1283 * Otherwise, just return the path as it is.
1284 *
1285 * @param $path string
1286 * @return string
1287 * @throws MWException
1288 */
1289 protected function resolveToStoragePath( $path ) {
1290 if ( $this->isVirtualUrl( $path ) ) {
1291 return $this->resolveVirtualUrl( $path );
1292 }
1293 return $path;
1294 }
1295
1296 /**
1297 * Get a local FS copy of a file with a given virtual URL/storage path.
1298 * Temporary files may be purged when the file object falls out of scope.
1299 *
1300 * @param $virtualUrl string
1301 * @return TempFSFile|null Returns null on failure
1302 */
1303 public function getLocalCopy( $virtualUrl ) {
1304 $path = $this->resolveToStoragePath( $virtualUrl );
1305 return $this->backend->getLocalCopy( array( 'src' => $path ) );
1306 }
1307
1308 /**
1309 * Get a local FS file with a given virtual URL/storage path.
1310 * The file is either an original or a copy. It should not be changed.
1311 * Temporary files may be purged when the file object falls out of scope.
1312 *
1313 * @param $virtualUrl string
1314 * @return FSFile|null Returns null on failure.
1315 */
1316 public function getLocalReference( $virtualUrl ) {
1317 $path = $this->resolveToStoragePath( $virtualUrl );
1318 return $this->backend->getLocalReference( array( 'src' => $path ) );
1319 }
1320
1321 /**
1322 * Get properties of a file with a given virtual URL/storage path.
1323 * Properties should ultimately be obtained via FSFile::getProps().
1324 *
1325 * @param $virtualUrl string
1326 * @return Array
1327 */
1328 public function getFileProps( $virtualUrl ) {
1329 $path = $this->resolveToStoragePath( $virtualUrl );
1330 return $this->backend->getFileProps( array( 'src' => $path ) );
1331 }
1332
1333 /**
1334 * Get the timestamp of a file with a given virtual URL/storage path
1335 *
1336 * @param $virtualUrl string
1337 * @return string|bool False on failure
1338 */
1339 public function getFileTimestamp( $virtualUrl ) {
1340 $path = $this->resolveToStoragePath( $virtualUrl );
1341 return $this->backend->getFileTimestamp( array( 'src' => $path ) );
1342 }
1343
1344 /**
1345 * Get the sha1 of a file with a given virtual URL/storage path
1346 *
1347 * @param $virtualUrl string
1348 * @return string|bool
1349 */
1350 public function getFileSha1( $virtualUrl ) {
1351 $path = $this->resolveToStoragePath( $virtualUrl );
1352 $tmpFile = $this->backend->getLocalReference( array( 'src' => $path ) );
1353 if ( !$tmpFile ) {
1354 return false;
1355 }
1356 return $tmpFile->getSha1Base36();
1357 }
1358
1359 /**
1360 * Attempt to stream a file with the given virtual URL/storage path
1361 *
1362 * @param $virtualUrl string
1363 * @param $headers Array Additional HTTP headers to send on success
1364 * @return bool Success
1365 */
1366 public function streamFile( $virtualUrl, $headers = array() ) {
1367 $path = $this->resolveToStoragePath( $virtualUrl );
1368 $params = array( 'src' => $path, 'headers' => $headers );
1369 return $this->backend->streamFile( $params )->isOK();
1370 }
1371
1372 /**
1373 * Call a callback function for every public regular file in the repository.
1374 * This only acts on the current version of files, not any old versions.
1375 * May use either the database or the filesystem.
1376 *
1377 * @param $callback Array|string
1378 * @return void
1379 */
1380 public function enumFiles( $callback ) {
1381 $this->enumFilesInStorage( $callback );
1382 }
1383
1384 /**
1385 * Call a callback function for every public file in the repository.
1386 * May use either the database or the filesystem.
1387 *
1388 * @param $callback Array|string
1389 * @return void
1390 */
1391 protected function enumFilesInStorage( $callback ) {
1392 $publicRoot = $this->getZonePath( 'public' );
1393 $numDirs = 1 << ( $this->hashLevels * 4 );
1394 // Use a priori assumptions about directory structure
1395 // to reduce the tree height of the scanning process.
1396 for ( $flatIndex = 0; $flatIndex < $numDirs; $flatIndex++ ) {
1397 $hexString = sprintf( "%0{$this->hashLevels}x", $flatIndex );
1398 $path = $publicRoot;
1399 for ( $hexPos = 0; $hexPos < $this->hashLevels; $hexPos++ ) {
1400 $path .= '/' . substr( $hexString, 0, $hexPos + 1 );
1401 }
1402 $iterator = $this->backend->getFileList( array( 'dir' => $path ) );
1403 foreach ( $iterator as $name ) {
1404 // Each item returned is a public file
1405 call_user_func( $callback, "{$path}/{$name}" );
1406 }
1407 }
1408 }
1409
1410 /**
1411 * Determine if a relative path is valid, i.e. not blank or involving directory traveral
1412 *
1413 * @param $filename string
1414 * @return bool
1415 */
1416 public function validateFilename( $filename ) {
1417 if ( strval( $filename ) == '' ) {
1418 return false;
1419 }
1420 return FileBackend::isPathTraversalFree( $filename );
1421 }
1422
1423 /**
1424 * Get a callback function to use for cleaning error message parameters
1425 *
1426 * @return Array
1427 */
1428 function getErrorCleanupFunction() {
1429 switch ( $this->pathDisclosureProtection ) {
1430 case 'none':
1431 case 'simple': // b/c
1432 $callback = array( $this, 'passThrough' );
1433 break;
1434 default: // 'paranoid'
1435 $callback = array( $this, 'paranoidClean' );
1436 }
1437 return $callback;
1438 }
1439
1440 /**
1441 * Path disclosure protection function
1442 *
1443 * @param $param string
1444 * @return string
1445 */
1446 function paranoidClean( $param ) {
1447 return '[hidden]';
1448 }
1449
1450 /**
1451 * Path disclosure protection function
1452 *
1453 * @param $param string
1454 * @return string
1455 */
1456 function passThrough( $param ) {
1457 return $param;
1458 }
1459
1460 /**
1461 * Create a new fatal error
1462 *
1463 * @return FileRepoStatus
1464 */
1465 public function newFatal( $message /*, parameters...*/ ) {
1466 $params = func_get_args();
1467 array_unshift( $params, $this );
1468 return MWInit::callStaticMethod( 'FileRepoStatus', 'newFatal', $params );
1469 }
1470
1471 /**
1472 * Create a new good result
1473 *
1474 * @param $value null|string
1475 * @return FileRepoStatus
1476 */
1477 public function newGood( $value = null ) {
1478 return FileRepoStatus::newGood( $this, $value );
1479 }
1480
1481 /**
1482 * Checks if there is a redirect named as $title. If there is, return the
1483 * title object. If not, return false.
1484 * STUB
1485 *
1486 * @param $title Title of image
1487 * @return Bool
1488 */
1489 public function checkRedirect( Title $title ) {
1490 return false;
1491 }
1492
1493 /**
1494 * Invalidates image redirect cache related to that image
1495 * Doesn't do anything for repositories that don't support image redirects.
1496 *
1497 * STUB
1498 * @param $title Title of image
1499 */
1500 public function invalidateImageRedirect( Title $title ) {}
1501
1502 /**
1503 * Get the human-readable name of the repo
1504 *
1505 * @return string
1506 */
1507 public function getDisplayName() {
1508 // We don't name our own repo, return nothing
1509 if ( $this->isLocal() ) {
1510 return null;
1511 }
1512 // 'shared-repo-name-wikimediacommons' is used when $wgUseInstantCommons = true
1513 return wfMessageFallback( 'shared-repo-name-' . $this->name, 'shared-repo' )->text();
1514 }
1515
1516 /**
1517 * Returns true if this the local file repository.
1518 *
1519 * @return bool
1520 */
1521 public function isLocal() {
1522 return $this->getName() == 'local';
1523 }
1524
1525 /**
1526 * Get a key on the primary cache for this repository.
1527 * Returns false if the repository's cache is not accessible at this site.
1528 * The parameters are the parts of the key, as for wfMemcKey().
1529 *
1530 * STUB
1531 * @return bool
1532 */
1533 public function getSharedCacheKey( /*...*/ ) {
1534 return false;
1535 }
1536
1537 /**
1538 * Get a key for this repo in the local cache domain. These cache keys are
1539 * not shared with remote instances of the repo.
1540 * The parameters are the parts of the key, as for wfMemcKey().
1541 *
1542 * @return string
1543 */
1544 public function getLocalCacheKey( /*...*/ ) {
1545 $args = func_get_args();
1546 array_unshift( $args, 'filerepo', $this->getName() );
1547 return call_user_func_array( 'wfMemcKey', $args );
1548 }
1549
1550 /**
1551 * Get an temporary FileRepo associated with this repo.
1552 * Files will be created in the temp zone of this repo and
1553 * thumbnails in a /temp subdirectory in thumb zone of this repo.
1554 * It will have the same backend as this repo.
1555 *
1556 * @return TempFileRepo
1557 */
1558 public function getTempRepo() {
1559 return new TempFileRepo( array(
1560 'name' => "{$this->name}-temp",
1561 'backend' => $this->backend,
1562 'zones' => array(
1563 'public' => array(
1564 'container' => $this->zones['temp']['container'],
1565 'directory' => $this->zones['temp']['directory']
1566 ),
1567 'thumb' => array(
1568 'container' => $this->zones['thumb']['container'],
1569 'directory' => ( $this->zones['thumb']['directory'] == '' )
1570 ? 'temp'
1571 : $this->zones['thumb']['directory'] . '/temp'
1572 )
1573 ),
1574 'url' => $this->getZoneUrl( 'temp' ),
1575 'thumbUrl' => $this->getZoneUrl( 'thumb' ) . '/temp',
1576 'hashLevels' => $this->hashLevels // performance
1577 ) );
1578 }
1579
1580 /**
1581 * Get an UploadStash associated with this repo.
1582 *
1583 * @return UploadStash
1584 */
1585 public function getUploadStash() {
1586 return new UploadStash( $this );
1587 }
1588
1589 /**
1590 * Throw an exception if this repo is read-only by design.
1591 * This does not and should not check getReadOnlyReason().
1592 *
1593 * @return void
1594 * @throws MWException
1595 */
1596 protected function assertWritableRepo() {}
1597 }
1598
1599 /**
1600 * FileRepo for temporary files created via FileRepo::getTempRepo()
1601 */
1602 class TempFileRepo extends FileRepo {
1603 public function getTempRepo() {
1604 throw new MWException( "Cannot get a temp repo from a temp repo." );
1605 }
1606 }